import React, { Fragment, useCallback } from "react";
import { useEnhanceSelector } from "@/hooks";
import { Navigate, useLocation } from "react-router-dom";
import Nprogress from "nprogress";

interface AuthRouterProps {
   children: React.ReactNode;
}

const AuthRouter: React.FunctionComponent<AuthRouterProps> = ({ children }) => {
   const location = useLocation();
   const withListPage: string[] = ["/", "/login", "/home", "/user", "/category", "/search", "/good-detail", "/good-list", "/comment-list"];
   const token: string = useEnhanceSelector(state => state.loginStore.loginData).token;

   /**
    * @description 权限控制的回调函数
    * */
   const isAuth = useCallback(() => {
      Nprogress.start();
      if (token) {
         if (location.pathname === "/login") {
            Nprogress.done();
            console.log("已经登录");
            return <Navigate to="/" />;
         } else {
            Nprogress.done();
            console.log("正常放行");
            return children;
         }
      } else {
         if (withListPage.includes(location.pathname)) {
            Nprogress.done();
            console.log("正常放行");
            return children;
         } else {
            Nprogress.done();
            console.log("请您登录");
            return <Navigate to="/login" />;
         }
      }
   }, [location.pathname]);
   return (
      <Fragment>
         {
            isAuth()
         }
      </Fragment>
   );
};

export default AuthRouter;
